package com.example.day_day_up.service.impl;

import com.example.day_day_up.entity.vo.OnlineExamVO;
import com.example.day_day_up.entity.vo.WebExamVO;
import com.example.day_day_up.entity.po.Exam;
import com.example.day_day_up.entity.po.ExamStatus;
import com.example.day_day_up.mappers.ExamMapper;
import com.example.day_day_up.mappers.ExamStatusMapper;
import com.example.day_day_up.service.ExamService;
import com.example.day_day_up.utils.DateUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ExamServiceImpl implements ExamService {
    private final ExamMapper examMapper;
    private final ExamStatusMapper examStatusMapper;

    public ExamServiceImpl(ExamMapper examMapper, ExamStatusMapper examStatusMapper) {
        this.examMapper = examMapper;
        this.examStatusMapper = examStatusMapper;
    }


    @Override
    public OnlineExamVO getExamById(String id) {
        Exam exam = examMapper.selectByID(id);
        OnlineExamVO examDTO = new OnlineExamVO();
        examDTO.setId(exam.getId());
        examDTO.setTitle(exam.getTitle());
        // 获取当前时间并加上testTime，得到考试结束时间
        long endTime = System.currentTimeMillis() + exam.getTestTime() * 60 * 1000;
        Date endTimeDate = new Date(endTime);
        examDTO.setTestTime(DateUtils.transToStr(endTimeDate));
        examDTO.setCourseId(exam.getCourseId());

        // TODO
        // 根据考试id获取题目
        examDTO.setQuestionNum(10);
        return examDTO;
    }

    @Override
    public List<WebExamVO> getExamsByCIDAndUID(String cId, String uId) {
        List<Exam> exams = examMapper.selectByCID(cId);
        // 遍历考试列表，获取每个考试的状态并封装成WebExamDTO对象
        List<WebExamVO> examDTOS = new ArrayList<>();
        for (Exam exam : exams) {
            WebExamVO examDTO = new WebExamVO();
            examDTO.setId(exam.getId());
            examDTO.setStatus(getStatus(exam.getId(), uId));
            examDTO.setTitle(exam.getTitle());
            examDTO.setDegree(exam.getDegree());
            // 获取已完成该考试的学生数量
            int finishCount = examStatusMapper.selectCountByEID(exam.getId());
            examDTO.setFinishCount(finishCount);
            examDTO.setCreateTime(DateUtils.transToStr(exam.getCreateTime()));
            examDTO.setTestTime(exam.getTestTime());
            examDTO.setCourseId(cId);
            examDTOS.add(examDTO);
        }
        return examDTOS;
    }

    // 根据考试id和用户id获取考试状态
    private Boolean getStatus(String eId, String uId) {
        ExamStatus status = examStatusMapper.selectByEIDAndUID(eId, uId);
        // 如果考试状态不存在，则插入一条新的状态并返回false
        if (status == null) {
            status = new ExamStatus(eId, uId, false);
            examStatusMapper.insert(status);
            return false;
        }
        return status.getStatus();
    }
}
